package com.qihetimes.earthangel.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis配置
 *
 * @author ：f4cklangzi@gmail.com
 * @date ：Created At 2021/12/4
 */
@Configuration
public class RedisConfig {
    
    @Resource
    RedisConnectionFactory redisConnectionFactory;
    
    @Value("${spring.profiles.active}")
    private String profile;
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisSerializer<Object> serializer = redisSerializer();
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new PrefixStringRedisSerializer(profile + ":"));
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new PrefixStringRedisSerializer(profile + ":"));
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    
    private RedisSerializer<Object> redisSerializer() {
        //创建JSON序列化器
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //必须设置，否则无法将JSON转化为对象，会转化成Map类型
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }
    
    @EqualsAndHashCode(callSuper = true)
    @Data
    @Slf4j
    private static class PrefixStringRedisSerializer extends StringRedisSerializer {
        
        private static final Charset CHARSET = StandardCharsets.UTF_8;
        private final String preFix;
        
        public PrefixStringRedisSerializer(String preFix) {
            this.preFix = preFix;
        }
        
        @Override
        public String deserialize(byte[] bytes) {
            String saveKey = new String(bytes, CHARSET);
            int indexOf = saveKey.indexOf(preFix);
            if (indexOf > 0) {
                log.error("key缺少前缀");
            } else {
                saveKey = saveKey.substring(indexOf);
            }
            return saveKey;
        }
        
        @Override
        public byte[] serialize(String string) {
            String key = preFix + string;
            return key.getBytes(CHARSET);
        }
    }
}
